#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    socket = new QUdpSocket(this);
    this->setWindowTitle("服务器");

    connect(socket, &QUdpSocket::readyRead, this, &Widget::processRequest);

    bool ret = socket->bind(QHostAddress::Any, 8080);
    if(!ret)
    {
        QMessageBox::critical(nullptr, "服务器出错", socket->errorString());
        return;
    }

}

Widget::~Widget()
{
    delete ui;
}

void Widget::processRequest()
{
    const QNetworkDatagram& req = socket->receiveDatagram();
    QString request = req.data();

    const QString& response = process(request);
    QNetworkDatagram responsedata(response.toUtf8(), req.senderAddress(), req.senderPort());
    socket->writeDatagram(responsedata);

}

QString Widget::process(const QString &request)
{
    return request;
}

